package com.linln.admin.pcs.controller;


import com.linln.admin.system.service.AppService;
import com.linln.common.data.QuerySpec;
import com.linln.common.utils.DateUtils;
import com.linln.common.utils.SnowflakeIdGenerator;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.domain.*;
import com.linln.modules.system.repository.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.data.domain.Pageable;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * 系统首页
 */
@Controller
@RequestMapping("/pcs/index")
public class Index {

    @Autowired
    private AppService appService;
    @Autowired
    private  ProjectRepository projectRepository;
    @Autowired
    private CompanyRepository companyRepository;
    @Autowired
    private PorterRepository porterRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private ComplainRepository complainRepository;
    @Autowired
    private EvaluateRepository evaluateRepository;
    @Autowired
    private PorterPermissionRepository porterPermissionRepository;
    @Autowired
    private ContractTplRepository contractTplRepository;
    @Autowired
    private OrderPortersRepository orderPortersRepository;



    /**
     * 陪护公司页面
     */
    @GetMapping("/index")
    @RequiresPermissions("pcs:index:index")
    public String index(Model model) throws Exception {


        // 待确认订单
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("orderStatus", QuerySpec.EQUAL, String.valueOf(0))
                .withMatcherValue("type", QuerySpec.EQUAL, String.valueOf(1));

        //服务中订单
        QuerySpec querySpec1 = QuerySpec.matching();
        querySpec1.withMatcherValue("orderStatus", QuerySpec.EQUAL, String.valueOf(2))
                .withMatcherValue("type", QuerySpec.EQUAL, String.valueOf(1));


        //客户投诉
        QuerySpec querySpec2 = QuerySpec.matching();


        User user = ShiroUtil.getSubject();
        model.addAttribute("userNickname",user.getNickname());
        Long companyId = null;
        String type= user.getType();
        if (type!= null && type.equals("2")) {
            companyId = user.getCompanyId();
            querySpec.withMatcherValue("companyId", QuerySpec.EQUAL, companyId.toString());
            querySpec1.withMatcherValue("companyId", QuerySpec.EQUAL, companyId.toString());
            querySpec2.withMatcherValue("companyId", QuerySpec.EQUAL, companyId.toString());
        }else if(type!= null && type.equals("1")){
            querySpec1.withMatcherValue("depId", QuerySpec.EQUAL, user.getDepId());
        }
        //待确认订单
        Long dqr_order_count = orderRepository.count(QuerySpec.of(querySpec));
        //服务中订单
        Long fwz_order_count = orderRepository.count(QuerySpec.of(querySpec1));
        //客户投诉
        Long complain_order_count = complainRepository.count(QuerySpec.of(querySpec2));
        model.addAttribute("dqr_order_count", dqr_order_count);
        model.addAttribute("fwz_order_count", fwz_order_count);
        model.addAttribute("complain_order_count", complain_order_count);



        if(type!= null && type.equals("1")){
            //护士长端特殊处理
            //查询待确认权限
            QuerySpec querySpec3 = QuerySpec.matching();
            querySpec3.withMatcherValue("depId", QuerySpec.EQUAL, user.getDepId())
                    .withMatcherValue("verifyStatus", QuerySpec.EQUAL, "0");
            Long porterPermission =  porterPermissionRepository.count(QuerySpec.of(querySpec3));
            model.addAttribute("porterPermission", porterPermission);
            //分组查询服务中的护工
            QuerySpec querySpecHg  = QuerySpec.matching();
            querySpecHg.withMatcherValue("depId", QuerySpec.EQUAL, user.getDepId())
                    .withMatcherValue("orderStatus", QuerySpec.EQUAL, "2")
                    .withMatcherValue("type", QuerySpec.EQUAL, "1");
            List<Order> orderPorters = orderRepository.findAll(QuerySpec.of(querySpecHg));
            if(orderPorters.size()>0){
                // 按护工ID分组订单
                Map<Long, List<Order>> porterOrdersMap = orderPorters.stream()
                        .collect(Collectors.groupingBy(Order::getPorterId));
                List<Map<String, Object>> porterList = new ArrayList<>();

                for (Map.Entry<Long, List<Order>> entry : porterOrdersMap.entrySet()) {
                    Long porterId = entry.getKey();
                    List<Order> orders = entry.getValue();

                    Map<String, Object> porterInfo = new HashMap<>();
                    Order firstOrder = orders.get(0); // 获取第一个订单来获取护工信息
                    Porter porter = porterRepository.findById(porterId).orElse(null);
                    if (porter != null) {
                        porterInfo.put("Headimg",porter.getHeadimg());
                    }

                    // 护工名称
                    porterInfo.put("porterName", firstOrder.getPorterName());

                    // 服务人数
                    int serviceCount = orders.size();
                    porterInfo.put("serviceCount", serviceCount);

                    // 患者信息列表
                    List<Map<String, String>> patientList = orders.stream().map(order -> {
                        Map<String, String> patientInfo = new HashMap<>();
                        patientInfo.put("patientName", order.getPatientName());
                        patientInfo.put("bedNo", order.getBedNo());
                        patientInfo.put("depName", order.getDepName());
                        patientInfo.put("project_title", order.getProjectTitle());
                        return patientInfo;
                    }).collect(Collectors.toList());

                    porterInfo.put("patients", patientList);

                    porterList.add(porterInfo);
                }

                model.addAttribute("porterList", porterList);
            }


        }
        if(type == null || type.equals("0") || type.equals("-1")){
            //医院管理员
            //待审核合同
            QuerySpec querySpec4 = QuerySpec.matching();
            querySpec4.withMatcherValue("verifyStatus", QuerySpec.EQUAL, "0");
            Long contractTpl =  contractTplRepository.count(QuerySpec.of(querySpec4));
            //待审核陪护项目
            QuerySpec querySpec5 = QuerySpec.matching();
            querySpec5.withMatcherValue("verifyStatus", QuerySpec.EQUAL, "0").withMatcherValue("type", QuerySpec.EQUAL, "1");
            Long projectPh =  projectRepository.count(QuerySpec.of(querySpec5));
            //待审核陪诊陪检项目
            QuerySpec querySpec6 = QuerySpec.matching();
            List types = new ArrayList();
            types.add(2L);
            types.add(3L);
            querySpec6.withMatcherValue("verifyStatus", QuerySpec.EQUAL, "0").withMatcherIn("type", types);
            Long projectPz =  projectRepository.count(QuerySpec.of(querySpec6));
            model.addAttribute("contractTpl", contractTpl);
            model.addAttribute("projectPh", projectPh);
            model.addAttribute("projectPz", projectPz);
            //公司服务排行
            // 创建分页请求（包含排序）
            Pageable pageable1 = PageRequest.of(0, 15, Sort.by("completedOrderCount").descending());

            //服务排行
            List<Object> orderCompanyList = orderRepository.findCompletedOrdersByCompanyIdAndGroupByCompanyId(pageable1);
            // 转换逻辑（在现有代码后添加）
            AtomicInteger j = new AtomicInteger(1);
            List<Map<String, Object>> resultCompanyList = orderCompanyList.stream().map(obj -> {
                // 假设查询结果返回的是Object数组，格式为 [porterId, completedOrderCount]
                Object[] row = (Object[]) obj;
                Map<String, Object> map = new HashMap<>();
                Company  company = companyRepository.findById(Long.parseLong(row[0].toString())).get();
                map.put("no", j.getAndIncrement());
                map.put("companyName",company.getName());
                map.put("completedOrderCount", row[1]);// 完成订单数
                return map;
            }).collect(Collectors.toList());
            model.addAttribute("fw_ranking", resultCompanyList);
        }else{
            // 创建分页请求（包含排序）
            Pageable pageable = PageRequest.of(0, 15, Sort.by("completedOrderCount").descending());

            //服务排行
            List<Object> orderList = orderRepository.findCompletedOrdersByCompanyIdAndGroupByPorterId(companyId, pageable);
            // 转换逻辑（在现有代码后添加）
            AtomicInteger i = new AtomicInteger(1);
            List<Map<String, Object>> resultList = orderList.stream().map(obj -> {
                // 假设查询结果返回的是Object数组，格式为 [porterId, completedOrderCount]
                Object[] row = (Object[]) obj;
                Map<String, Object> map = new HashMap<>();
                Porter porter = porterRepository.findById(Long.parseLong(row[0].toString())).get();
                map.put("no", i.getAndIncrement());
                map.put("porterName",porter.getName());
                map.put("headimg", porter.getHeadimg());
                map.put("completedOrderCount", row[1]);// 完成订单数
                return map;
            }).collect(Collectors.toList());
            model.addAttribute("fw_ranking", resultList);
        }



        if(type!= null && type.equals("2")){
            return "/pcs/index/index";
        } else if (type!= null && type.equals("1")) {
            return "/pcs/index/index_hsz";
        }else {
            return "/pcs/index/index_yy";
        }


    }

    //本年服务费用按月统计
    @GetMapping("/getServiceCost")
    public ResponseEntity<?> getServiceCost() throws Exception {
        User user = ShiroUtil.getSubject();
        Long companyId = null;
        if (user.getType() != null && user.getType().equals("2")) {
            companyId = user.getCompanyId();
        }
        //获取当前年份
        String year = DateUtils.getYear();
        List<Object[]> result = orderRepository.findNumByMonth(companyId);
        // 转换金额单位并收集数据
        List<Long> num = new ArrayList<>();
        List<String> months = new ArrayList<>();

        for (Object[] row : result) {
            if (row.length >= 2) {
                num.add( (Long) row[0]);
                months.add((String) row[1]);
            }
        }

        // 构建返回结构
        Map<String, Object> response = new HashMap<>();
        response.put("num", num);
        response.put("months", months);

        return ResponseEntity.ok(response);
    }

    //获取不同类型订单数量
    @GetMapping("/getOrderCount")
    public ResponseEntity<?> getOrderCount() throws Exception {
        User user = ShiroUtil.getSubject();
        Long companyId = null;
        if (user.getType() != null && user.getType().equals("2")) {
            companyId = user.getCompanyId();
        }

        List<Object[]> result =  orderRepository.findCompletedOrdersByCompanyIdAndGroupByType(companyId);
        List<Map<String, Object>> resultList = result.stream().map(obj -> {
            Object[] row = (Object[]) obj;
            Map<String, Object> map = new HashMap<>();
            switch ((Integer) row[0]){
                case 1:
                    map.put("name", "陪护服务");
                    map.put("value", row[1]);
                    break;
                case 2:
                    map.put("name", "陪诊服务");
                    map.put("value", row[1]);
                    break;
                case 3:
                    map.put("name", "陪检服务");
                    map.put("value", row[1]);
                    break;
            }
            return map;
        }).collect(Collectors.toList());
        return ResponseEntity.ok(resultList);
    }

    //评分统计
    @GetMapping("/getScore")
    public ResponseEntity<?> getScore() throws Exception {
        User user = ShiroUtil.getSubject();
        Long companyId = null;
        if (user.getType() != null && user.getType().equals("2")) {
            companyId = user.getCompanyId();
        }
        List<Object[]> result =  evaluateRepository.countByCompany(companyId);

        // 转换金额单位并收集数据
        List<String> value = new ArrayList<>();
        List<String> category = new ArrayList<>();
        for (Object[] row : result) {
            if (row.length >= 2) {
                value.add( String.valueOf(row[1]));
                category.add( row[0]+"分");
            }
        }
        Map<String, Object> response = new HashMap<>();
        response.put("category", category);
        response.put("value", value);
        return ResponseEntity.ok(response);
    }


    @GetMapping("/testData")
    public ResponseEntity<?> testData() throws Exception {
        List<Porter> porterList = porterRepository.findAll();
        porterList.forEach(porter -> {
            Order order = new Order();
            order.setPorterId(porter.getId());
            order.setPorterName(porter.getName());
            order.setProjectTitle("CT检查");
            order.setPatientId(7l);
            order.setPatientName("王群");
            order.setProjectId(11l);
            order.setStartDay("2025-04-23 17:30");
            order.setOrderStatus(6);
            order.setCompanyId(5l);
            order.setType(2);
            SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
            long l = idGenerator.nextId();
            order.setSn("NO"+l);
            order.setPayStatus((byte) 1);
            order.setStatus((byte) 1);
            order.setPhone("B437EC25B672AB73FDE1D234CA4E82073A45161E0B837067CE73365AE3C726DA277B42DF74EBC03A1ECC3B5D9910ED4B");
            order.setPorterPhone(porter.getPhone());
            order.setPrice(30.00);
            order.setTotal(30.00);
            Order order1 =  orderRepository.save(order);
            OrderPorters orderPorters = new OrderPorters();
            orderPorters.setOrderId(order1.getId());
            orderPorters.setCompanyId(order1.getCompanyId());
            orderPorters.setPorterId(porter.getId());
            orderPorters.setServiceStatus(2);
            orderPorters.setTimeStar("2025-04-23 17:30:00");
            orderPorters.setTimeEnd("2025-04-23 18:30:00");
            orderPorters.setType(1);
            orderPorters.setOrderType(2);
            orderPorters.setStatus((byte) 1);
            orderPortersRepository.save(orderPorters);

        });
        return ResponseEntity.ok("成功");
    }




}
